<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-row type="flex" justify="space-between" align="middle">
          <el-form :inline="true">
            <el-form-item label="姓名">
              <el-input v-model="searchItem.studentname" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="学号">
              <el-input v-model="searchItem.studentid" placeholder="学号" />
            </el-form-item>
            <el-form-item label="学院">
              <el-input v-model="searchItem.college" placeholder="学院" />
            </el-form-item>
            <el-form-item label="班级">
              <el-input v-model="searchItem.classname" placeholder="班级" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="searchHandle">搜索</el-button>
              <el-button icon="el-icon-refresh-left" @click="restHandle">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-card>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading" class="page-tools">
        <page-tools :show-before="true">
          <span slot="before">共{{ page.total }}条记录</span>
          <template slot="after">
            <el-button :disabled="!checkPermission('api-user-post')" size="small" type="primary" @click="$router.push(`/users/adduser`)">新增用户</el-button>
          </template>
        </page-tools>
        <el-table border :data="userlist" stripe highlight-current-row>
          <el-table-column label="头像" prop="photoid" width="60" align="center">
            <template slot-scope="scope">
              <el-image
                :src="`http://124.222.15.71:8191/api/hold/imgdownload?fileName=${scope.row.photo}`"
                :preview-src-list="[`http://124.222.15.71:8191/api/hold/imgdownload?fileName=${scope.row.photo}`]"
                fit="fill"
                :lazy="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="studentname" align="center" />
          <el-table-column label="学号" prop="studentid" align="center" />
          <el-table-column label="班级" prop="classname" align="center" />
          <el-table-column label="学院" prop="college" align="center" />
          <el-table-column label="添加时间" prop="jointime" sortable align="center" />
          <el-table-column label="电话号码" prop="phone" align="center" />
          <el-table-column label="操作" fixed="right" width="250" align="center">
            <template slot-scope="scope">
              <el-button :disabled="!checkPermission('api-userdetail-get')" type="success" size="small" @click="$router.push(`/users/detail/${scope.row.studentid}`)">查看</el-button>
              <el-button :disabled="!checkPermission('api-userrole-get')" type="primary" size="small" @click="chooseRole(scope.row.studentid)">角色</el-button>
              <el-button :disabled="!checkPermission('api-user-delete')" type="danger" size="small" @click="deleteUser(scope.row.studentid)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[1, 5, 10, 20]"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
            @size-change="handleSizeChange"
          />
        </el-row>
        <!--弹出分配角色框-->
        <el-dialog
          title="分配角色"
          :visible.sync="dialogVisible"
          width="30%"
          @closed="cleardata"
        >
          <el-checkbox-group v-model="checkList">
            <el-checkbox v-for="item in rolelist" :key="item.roleid" :label="item.name" />
          </el-checkbox-group>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cleardata">取 消</el-button>
            <el-button :disabled="!checkPermission('api-userrole-put')" type="primary" @click="updateUserRole">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getAllUser, delUser, getUserRole } from '@/api/user'
import { getAllRole, addUserRole } from '@/api/role'

export default {
  data() {
    return {
      searchItem: {
        studentname: '',
        studentid: '',
        classname: '',
        college: ''
      },
      loading: false,
      userlist: [], // 用户列表
      page: {
        page: 1, // 当前页码
        size: 5,
        total: 0 // 总数
      },
      dialogVisible: false,
      checkList: ['1'],
      rolelist: [],
      // 获取到的用户角色
      userroles: [],
      // 存储用户id和角色字符串
      userrole: { user_id: '', role_id: '' }
    }
  },
  created() {
    this.getUserList()
    this.getRoleList()
  },
  methods: {
    changePage(newPage) {
      this.page.page = newPage
      this.getUserList()
    },
    handleSizeChange(newSize) {
      this.page.size = newSize
      this.getUserList()
    },
    searchHandle() {
      const searchItem = {}
      for (const key in this.searchItem) {
        if (this.searchItem[key] !== '') {
          searchItem[key] = this.searchItem[key]
        }
      }
      this.getUserList(searchItem)
    },
    restHandle() {
      this.searchItem.studentname = ''
      this.searchItem.studentid = ''
      this.searchItem.classname = ''
      this.searchItem.college = ''
      this.getUserList()
    },
    async getUserList(searchItem) {
      this.loading = true
      const { total, rows } = await getAllUser(this.page.page, this.page.size, searchItem)
      this.page.total = total
      this.userlist = rows
      this.loading = false
    },
    deleteUser(id) {
      this.$confirm('确定要删除该用户吗？').then(() => {
        // 如果点击了确定就会进入then
        return delUser(id) // 返回promise对象
      }).then(() => {
        this.$message.success('删除用户成功！')
        this.getUserList()
      })
    },
    async getRoleList() {
      const { rows } = await getAllRole(1, 999)
      this.rolelist = rows
    },
    async chooseRole(id) {
      this.userroles = await getUserRole(id)
      this.userroles.forEach(val => {
        this.checkList.push(val.name)
      })
      this.dialogVisible = true
      this.userrole.user_id = id
    },
    updateUserRole() {
      var rolearr = []
      this.rolelist.forEach(val => {
        if (this.checkList.indexOf(val.name) !== -1) {
          rolearr.push(val.roleid)
        }
      })
      this.userrole.role_id = rolearr.join('-')
      this.$confirm('确定要更改该用户权限吗？').then(() => {
        // 如果点击了确定就会进入then
        return addUserRole(this.userrole) // 返回promise对象
      }).then(() => {
        this.$message.success('更改成功！')
        this.cleardata()
      })
    },
    cleardata() {
      this.userrole = { user_id: '', role_id: '' }
      this.dialogVisible = false
      this.checkList = []
      this.userroles = []
    }
  }
}
</script>

<style lang="less" scoped>

</style>
